import { getGradeList } from '@/api'
import { DefaultPagination } from '@/store/constant'
import { SelectChangeEvent } from '@mui/material'

interface Props {
  value: string
  onChange: (e: SelectChangeEvent) => void
  label?: string
  disabled?: boolean
}

const ITEM_HEIGHT = 36
const ITEM_PADDING_TOP = 8
const MenuProps = {
  PaperProps: {
    id: 'grade-select-paper',
    style: {
      maxHeight: ITEM_HEIGHT * 10 + ITEM_PADDING_TOP,
      width: 250
    }
  }
}

const GradeSelect = ({ value, onChange, label = '职级', disabled = false }: Props) => {
  const getLoadMoreList = async (page: number, pageSize: number) => {
    const res = await getGradeList({ page, size: pageSize })
    return res
      ? {
          list: res.data,
          page: res.page
        }
      : undefined
  }

  const { data, loadMore, loadingMore, noMore } = useInfiniteScroll(
    // @ts-ignore
    (d) => {
      const page = d ? d.page + 1 : 1
      return getLoadMoreList(page, DefaultPagination.pageSize)
    },
    {
      target: () => document.getElementById('grade-select-paper'),
      isNoMore: (d) => (d ? d.list.length < DefaultPagination.pageSize * d.page : undefined)
    }
  )

  return (
    <FormControl fullWidth disabled={disabled}>
      <InputLabel id="grade-stage-label">{label}</InputLabel>
      <Select MenuProps={MenuProps} label={label} labelId="grade-stage" onChange={onChange} value={value}>
        {(data?.list ?? [{ grade: value }]).map((item, index) => (
          <MenuItem key={index} value={item.grade}>
            <Typography variant="button">{item.grade}</Typography>
          </MenuItem>
        ))}
        <Box style={{ marginTop: 8, textAlign: 'center' }}>
          {!noMore && (
            <Button type="button" onClick={loadMore} disabled={loadingMore}>
              {loadingMore ? 'Loading more...' : 'Click to load more'}
            </Button>
          )}
          {noMore && <Typography variant="body2">No more data</Typography>}
        </Box>
      </Select>
    </FormControl>
  )
}

export default GradeSelect
